<template>
    <div class="table-header">
        <el-input placeholder="请输入账号" v-model="inputVal" @keyup.enter="search">
            <template #append>
                <el-button :icon="SearchOutlined" @click="search" />
            </template>
        </el-input>
        <el-button type="primary" @click="addDialogFormVisible = true">添加用户</el-button>
        <!-- 添加用户对话框 -->
        <el-dialog v-model="addDialogFormVisible" title="添加用户">
            <el-form :model="addForm" :rules="addRules" ref="addRuleFormRef">
                <!-- <el-form :model="addForm" :rules="rules" ref="ruleFormRef"> -->
                <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                    <el-input v-model="addForm.username" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                    <el-input v-model="addForm.password" autocomplete="off" type="password" />
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
                    <el-radio-group v-model="addForm.status">
                        <el-radio label="正常" :value="1"></el-radio>
                        <el-radio label="禁用" :value="0"></el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="addSubmitForm(addRuleFormRef)">提交</el-button>
                    <el-button @click="addResetForm(addRuleFormRef)">
                        重置
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column label="头像">
            <template #default="scope">
                <img :src="scope.row.avatar" style="width: 50px; height: 50px;" />
            </template>
        </el-table-column>
        <el-table-column label="密码">
            <template #default="scope">
                {{ '*'.repeat(6) }}
            </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别">
            <template #default="scope">
                {{ scope.row.gender === 1 ? '男' : '女' }}
            </template>
        </el-table-column>
        <el-table-column prop="sign" label="签名" />
        <el-table-column prop="status" label="状态">
            <template #default="scope">
                <el-switch v-model="scope.row.status" @change="changeState(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
            <template #default="scope">
                <el-button type="primary" :icon="EditOutlined" @click="editUser(scope.row)"></el-button>
                <el-popconfirm width="220" confirm-button-text="是的" cancel-button-text="不, 谢谢" :icon="InfoFilled"
                    icon-color="#626AEF" title="你确定要删除这条数据吗?" @onConfirm="deleteuser(scope.row)"
                    @confirm="deleteuser(scope.row)">
                    <template #reference>
                        <el-button type="danger" :icon="DeleteOutlined"></el-button>
                    </template>
                </el-popconfirm>
            </template>
        </el-table-column>
    </el-table>
    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editDialogFormVisible" title="编辑用户">
        <el-form :model="editForm" :rules="editRules" ref="editRuleFormRef">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                <el-input v-model="editForm.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                <el-input v-model="editForm.password" autocomplete="off" type="password"/>
            </el-form-item>
            <el-form-item label="昵称" :label-width="formLabelWidth" prop="nick">
                <el-input v-model="editForm.nick" autocomplete="off" />
            </el-form-item>
            <el-form-item label="性别" :label-width="formLabelWidth" prop="gender">
                <el-radio-group v-model="editForm.gender">
                    <el-radio :label="0">女</el-radio>
                    <el-radio :label="1">男</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="头像" :label-width="formLabelWidth" prop="avatar">
                <el-upload class="avatar-uploader" action="http://localhost:9999/zzxcsm/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :on-error="handleAvatarError">
                    <img v-if="editForm.avatar" :src="editForm.avatar" class="avatar" style="width: 100px; height: 100px">
                    <img v-else style="width: 100px; height: 100px"
                        src="https://manz-1318365467.cos.ap-shanghai.myqcloud.com/logo/18c7dafa-495e-4749-b896-36e5b5d330c9.png" />
                </el-upload>
            </el-form-item>
            <el-form-item label="签名" :label-width="formLabelWidth" prop="sign">
                <el-input v-model="editForm.sign" autocomplete="off" />
            </el-form-item>
            <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
                <el-radio-group v-model="editForm.status">
                    <el-radio :label="true">正常</el-radio>
                    <el-radio :label="false">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="editSubmitForm(editRuleFormRef)">提交</el-button>
                <el-button @click="editResetForm(editRuleFormRef)">
                    重置
                </el-button>
            </span>
        </template>
    </el-dialog>
    <!-- 编辑对话框 -->
    <!-- 分页 -->
    <el-pagination v-model:currentPage="currentPage" v-model:pageSize="pageSize" :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
</template>

<script setup>
/* 导入插件 */
import { DeleteOutlined, EditOutlined, SearchOutlined, SettingOutlined } from '@ant-design/icons-vue';
import { InfoFilled } from '@element-plus/icons-vue'
import axios from '../../axios.js';
import { ref, onBeforeMount, watchEffect, reactive } from 'vue'
import { ElMessage } from 'element-plus';
/* 分页 */
const total = ref(1)
const currentPage = ref(1)
const pageSize = ref(3)
const handleSizeChange = (val) => {
    console.log(`${val} items per page`)
    pageSize.value = val
}
const handleCurrentChange = (val) => { console.log(`current page:${val}`); currentPage.value = val }
/* 获取用户数据 */
const tableData = ref([]);
let netData = ref([])
const getuser = async () => {
    const { data: res } = await axios.get(`user/page?page=${currentPage.value}&pageSize=${pageSize.value}`)
    tableData.value = [];
    res.data.records.forEach(ele => {
        tableData.value.push({
            id: ele.idZzxcsm,
            username: ele.usernameZzxcsm,
            password: ele.passwordZzxcsm,
            nick: ele.nickZzxcsm,
            avatar: ele.avatarZzxcsm,
            gender: ele.genderZzxcsm,
            sign: ele.signZzxcsm,
            status: ele.statusZzxcsm === 1 ? true : false
        })
    })
    total.value = res.data.total;
    netData.value = tableData.value
}
getuser()
/* 搜索框 */
const inputVal = ref('')
const search = () => tableData.value = netData.value.filter(val => val.username.indexOf(inputVal.value) != -1)
/* 切换用户状态 */
const changeState = async (user) => {
    console.log(user);
    var s = user.status === true ? 1 : 0
    const { data: res } = await axios.put(`user/${user.id}/status/${s}`)
}
/* 新建用户 */
const formLabelWidth = '140px';
const addDialogFormVisible = ref(false)
const addForm = reactive({
    username: '',
    password: '',
    avatar: '',
    sign: '',
    status: ''
})
// 表单验证
const addRuleFormRef = ref(null)
const addRules = reactive({
    username: [{
        required: true, message: '请输入用户名', trigger: 'blur'
    }, {
        min: 5, max: 10, message: '用户名长度在 5 到 10', trigger: 'blur'
    }],
    password: [{
        required: true, message: '请输入密码', trigger: 'blur'
    }, {
        min: 6, max: 12, message: '密码长度在 3 到 20', trigger: 'blur'
    }],
})
// 提交表单
const addSubmitForm = async (formEL) => {
    if (!formEL) return
    const { data: res } = await axios.post('/user/register', {
        usernameZzxcsm: addForm.username, passwordZzxcsm: addForm.password, statusZzxcsm: addForm.status === "正常" ? 1 : 0
    })
    if (res.code === 1) {
        getuser()
        addDialogFormVisible.value = false
        ElMessage.success("新建成功！")
    } else {
        ElMessage.error(res.msg)
    }

}
// 清空表单
const addResetForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields()
}
/* 编辑用户 */
const editDialogFormVisible = ref(false)
const editForm = reactive({
    username: '',
    password: '',
    nick: '',
    gender: '',
    avatar: '',
    sign: '',
    status: ''
})
const editUser = (user) => {
    editDialogFormVisible.value = true;
    editForm.id = user.id;
    editForm.username = user.username;
    editForm.password = user.password;
    editForm.nick = user.nick;
    editForm.gender = user.gender;
    editForm.avatar = user.avatar;
    editForm.sign = user.sign;
    editForm.status = user.status;
    console.log(editForm);
}
// 表单验证
const editRuleFormRef = ref(null)
const editRules = reactive({
    username: [{
        required: true, message: '请输入用户名', trigger: 'blur'
    }, {
        min: 5, max: 10, message: '用户名长度在 5 到 10', trigger: 'blur'
    }],
    password: [{
        required: true, message: '请输入密码', trigger: 'blur'
    }, {
        min: 6, max: 12, message: '密码长度在 6 到 12', trigger: 'blur'
    }],

})
// 提交表单
const editSubmitForm = async (formEL) => {
    if (!formEL) return
    console.log(editForm);
    const { data: res } = await axios.put('/user', {
        idZzxcsm: editForm.id,
        usernameZzxcsm: editForm.username,
        passwordZzxcsm: editForm.password,
        avatarZzxcsm: editForm.avatar,
        genderZzxcsm: editForm.gender,
        signZzxcsm: editForm.sign,
        statusZzxcsm: editForm.status === true ? 1 : 0
    })
    if (res.code === 1) {
        getuser()
        editDialogFormVisible.value = false
        ElMessage.success("修改成功！")
    } else {
        ElMessage.error(res.msg)
    }

}
// 清空表单
const editResetForm = (formEL) => {
    if (!formEL) return
    formEL.resetFields()
}
// 上传成功的处理逻辑
const handleAvatarSuccess = (res, file, fileList) => {
    editForm.avatar = res.data;
    ElMessage.success('头像上传成功');
};
// 上传失败的处理逻辑
const handleAvatarError = (err, file, fileList) => {
    ElMessage.error('头像上传失败');
};
/* 删除用户 */
const deleteuser = async (user) => {
    const { data: res } = await axios.delete(`/user/${user.id}`);
    getuser();
}

/* 设置刷新 */
onBeforeMount(() => {
    getuser();
})
watchEffect((currentPage, pageSize) => {
    getuser()
})

</script>

<style scoped>
.table-header {
    margin-bottom: 20px;
}

.table-header .el-input {
    width: 300px;
    margin-right: 20px;
}

.el-pagination {
    margin-top: 30px;
}

.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
